﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：ErrorInfoBuilder.cs
// 功能描述：TongTongMall.WebApi
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Authorization;
using TongTongMall.Dependecy;
using TongTongMall.UI;

namespace TongTongMall.WebApi.Models
{
    public class ErrorInfoBuilder : IErrorInfoBuilder, ISingletonDependency
    {

        public static IErrorInfoBuilder Instance { get { return IocManager.Instance.Resolve<IErrorInfoBuilder>(); } }


        /// <inheritdoc/>
        public ErrorInfo BuildForException(Exception exception)
        {
            if (exception is AggregateException && exception.InnerException != null)
            {
                var aggException = exception as AggregateException;
                if (aggException.InnerException is UserFriendlyException)
                {
                    exception = aggException.InnerException;
                }
            }

            if (exception is UserFriendlyException)
            {
                var userFriendlyException = exception as UserFriendlyException;
                return new ErrorInfo(userFriendlyException.Code, userFriendlyException.Message, userFriendlyException.Details);
            }

            if (exception is AuthorizationException)
            {
                var authorizationException = exception as AuthorizationException;
                return new ErrorInfo(authorizationException.Code, authorizationException.Message);
            }

            return new ErrorInfo("服务器发生错误！");
        }
    }
}
